package com.ls.lserp.modules.trade.service;



import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.dbaccess.Dao.FinanceEntityMapper;
import com.ls.lserp.dbaccess.Entity.FinanceEntity;
import com.ls.lserp.modules.order.dao.AuditInfoDao;
import com.ls.lserp.modules.order.dao.BigcargoOrderDao;
import com.ls.lserp.modules.order.dao.OrderDao;
import com.ls.lserp.modules.order.dao.SpecimenProductionDao;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.order.entity.Order;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.order.entity.SpecimenProduction;
import com.ls.lserp.modules.setting.dao.OgnizationDao;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.UserUtils;
import com.ls.lserp.modules.trade.entity.Enchase;

@Service
@Transactional(readOnly = true)
public class SettlementService extends CrudService<FinanceEntityMapper, FinanceEntity>{
	
    @Autowired
    private FinanceEntityMapper financeEntityMapper;
    //组织
    @Autowired
    private OgnizationDao ognizationDao;
    //大货合同
  	@Autowired
  	private BigcargoOrderDao bigcargoOrderDao ;
  	//定制合同
  	@Autowired
  	private OrderDao orderDao ;
  	// 样品生产
 	@Autowired
 	private SpecimenProductionDao specimenProductionDao;
	// 审核表
    @Autowired
    private AuditInfoDao  auditInfoDao;
    /**
	  * @Title: findList
	  * @Description: 一览查询
	  * @return Page<FinanceEntity> 
	  */
    public Page<FinanceEntity> findList(Page<FinanceEntity> page, FinanceEntity financeEntity) {
		// tab页分，检索条件设定(0:全部,1:已删除)
    	//待审核
    	if (financeEntity.getTabPageStatus() == 1) {
    		financeEntity.setOrderStatus("");
    		financeEntity.setAccountsStatus("");
    		financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_wait_accept"));
    	//未通过
    	}else if(financeEntity.getTabPageStatus() == 2) {
    		financeEntity.setOrderStatus("");
			financeEntity.setAccountsStatus("");
    		financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_no"));
    	//审核未完成
    	}else if(financeEntity.getTabPageStatus() == 3) {
    		financeEntity.setOrderStatus(ResourcesUtil.getConfig("financeOrderStatus_00"));
    		financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
    		financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
    	//审核部分完成
    	}else if(financeEntity.getTabPageStatus() == 4) {
    		financeEntity.setOrderStatus(ResourcesUtil.getConfig("financeOrderStatus_10"));
    		financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
    		financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
    	//完成未入账
		}else if(financeEntity.getTabPageStatus() == 5) {
			financeEntity.setOrderStatus(ResourcesUtil.getConfig("financeOrderStatus_20"));
			financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
    		financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
    	//完成已入账
		}else if(financeEntity.getTabPageStatus() == 6) {
			financeEntity.setOrderStatus(ResourcesUtil.getConfig("financeOrderStatus_20"));
			financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus01"));
    		financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
    	//全部
		}else {
			financeEntity.setOrderStatus("");
			financeEntity.setAccountsStatus("");
    		financeEntity.setAuditStatus("");
		}
        // 设置分页参数
    	financeEntity.setPage(page);
        // 执行分页查询
        page.setList(financeEntityMapper.findList(financeEntity));
        return page;
    }
    /**
	  * @Title: findUnrecordedList
	  * @Description: 一览查询审核未入账数据
	  * @return void 
	  * @throws
	  */
    public Page<FinanceEntity> findUnrecordedList(Page<FinanceEntity> page, FinanceEntity financeEntity) {
    	financeEntity.setTabPageStatus(3);
    	financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
		financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
        // 设置分页参数
    	financeEntity.setPage(page);
        // 执行分页查询
        page.setList(financeEntityMapper.findListForVoucher(financeEntity));
        return page;
    }
    
	/**
     * 导出发票
     *
     * @throws IOException
     */
    public ExcelTemplate exportProformaInvoice(FinanceEntity financeEntity , String tempFilePath) throws IOException {
    	// 返回值
    	ExcelTemplate handle = new ExcelTemplate();
    	//输出基本信息
    	printFinanceInfoTemp(tempFilePath,financeEntity,handle);
    	//大连振宇服装厂信息
    	Ognization companyInfo = ognizationDao.getOgnizationData(1L);
    	//客户信息
    	Ognization customerInfo = ognizationDao.getOgnizationData(financeEntity.getOgnizationId());
    	//输出大连振宇信息
    	printOgnizationInfoTemp(tempFilePath,companyInfo,handle,"_A");
    	//输出客户信息
    	printOgnizationInfoTemp(tempFilePath,customerInfo,handle,"_B");
    	//大货合同
    	if (ResourcesUtil.getConfig("financeCategory05").equals(financeEntity.getFinanceCategory())) {
    		List<BigcargoOrder> bigcargoOrderList = bigcargoOrderDao.findOrderList(financeEntity.getFinanceContractId());
    		printInvoiceStyleInfoTemp(tempFilePath,bigcargoOrderList,null,null,handle);
    	//样品生产
		}else if (ResourcesUtil.getConfig("financeCategory04").equals(financeEntity.getFinanceCategory())) {
			List<SpecimenProduction> specimenProductionList = new ArrayList<>();
			specimenProductionList.add(specimenProductionDao.get(financeEntity.getFinanceContractId()));
			printInvoiceStyleInfoTemp(tempFilePath,null,specimenProductionList,null,handle);
		//定制合同
		}else if (ResourcesUtil.getConfig("financeCategory06").equals(financeEntity.getFinanceCategory())) {
			Order order = new Order();
			order.setContractNo(financeEntity.getFinanceContractNo());
			List<Order> orderList = orderDao.findList(order);
			printInvoiceStyleInfoTemp(tempFilePath,null,null,orderList,handle);
		}
        
        return handle;

    }
    /**
     * 
     * @param tempFilePath
     * @param ognization
     * @param handle
     * @throws IOException
     */
    private void printFinanceInfoTemp(String tempFilePath, FinanceEntity financeEntity, ExcelTemplate handle) throws IOException {
    	List<String> dataCellDeclare = new ArrayList<String>();
        // 变量值
        Map<String, Object> dataMapResult = new HashMap<String, Object>();

        // 发票号
        dataCellDeclare.add("financeContractNo");
        dataMapResult.put("financeContractNo", financeEntity.getFinanceContractNo());
        // 发货日期
        dataCellDeclare.add("exportDate");
        dataMapResult.put("exportDate", DateUtils.getDate("yyyy-MM-dd"));
        // 货币种类
        dataCellDeclare.add("financeCurrency");
        dataMapResult.put("financeCurrency", DictUtils.getDictName(financeEntity.getFinanceCurrency()));
        // 总金额
        dataCellDeclare.add("creditAmount");
        dataMapResult.put("creditAmount", financeEntity.getCreditAmount());
        // 备注
        dataCellDeclare.add("remarks");
        dataMapResult.put("remarks", financeEntity.getRemarks());
        // 向excel表输出
        handle.writeData(tempFilePath, dataCellDeclare, dataMapResult, 0);
    }
    /**
     * 
     * @param tempFilePath
     * @param orderMateriel
     * @param handle
     * @throws IOException
     */
    private void printOgnizationInfoTemp(String tempFilePath, Ognization ognization, ExcelTemplate handle ,String oFlag) throws IOException {
    	List<String> dataCellDeclare = new ArrayList<String>();
        // 变量值
        Map<String, Object> dataMapResult = new HashMap<String, Object>();

        // 公司名称
        dataCellDeclare.add("ognizationName" + oFlag);
        dataMapResult.put("ognizationName" + oFlag, ognization.getOgnizationName());
        // 公司地址
        dataCellDeclare.add("ognizationAddress" + oFlag);
        dataMapResult.put("ognizationAddress" + oFlag, ognization.getOgnizationAddress());
        // 公司国家城市
        dataCellDeclare.add("ognizationCity" + oFlag);
        dataMapResult.put("ognizationCity" + oFlag, DictUtils.getDictName(ognization.getOgnizationCity()) + "-" + DictUtils.getDictName(ognization.getOgnizationCity()));
        // 公司邮编
        dataCellDeclare.add("ognizationZipCode" + oFlag);
        dataMapResult.put("ognizationZipCode" + oFlag, ognization.getOgnizationZipCode());
        // 公司电话
        dataCellDeclare.add("contactPhone" + oFlag);
        dataMapResult.put("contactPhone" + oFlag, ognization.getContactPhone());
        
        
        // 向excel表输出
        handle.writeData(tempFilePath, dataCellDeclare, dataMapResult, 0);
    }
    /**
     * 
     * @param tempFilePath
     * @param packageDetailsList
     * @param handle
     * @throws IOException
     */
    private void printInvoiceStyleInfoTemp(String tempFilePath, List<BigcargoOrder> bigcargoOrderList,List<SpecimenProduction> specimenProductionList, List<Order> orderList,ExcelTemplate handle) throws IOException {
        // 变量声明
        List<String> dataCellDeclare = new ArrayList<String>();
        // 变量值集合
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        // 款式编号
        dataCellDeclare.add("styleCustomerNo");
        // 款式名称
        dataCellDeclare.add("styleNameCN");
        // 成分
        dataCellDeclare.add("materialComposition");
        // 数量
        dataCellDeclare.add("indentQuantity");
        // 单价
        dataCellDeclare.add("indentPrice");
        // 总价
        dataCellDeclare.add("indentAmount");
        // 结果
        Map<String, Object> map;
        // 临时接收变量
        BigcargoOrder tempBean;
        SpecimenProduction tempBean_SP;
        Order tempBean_O;
        // 格式化数字
        NumberFormat num = NumberFormat.getInstance();
        if (bigcargoOrderList != null && bigcargoOrderList.size() > 0) {
        	for (int i = 0; i < bigcargoOrderList.size(); i++) {
        		if (bigcargoOrderList.get(i) != null) {
        			map = new HashMap<String, Object>();
        			tempBean = bigcargoOrderList.get(i);
        			// 款式编号
        			map.put("styleCustomerNo", tempBean.getStyleCustomerNo());
        			// 款式名称
        			map.put("styleNameCN", tempBean.getStyleNameCN());
        			// 成分
        			map.put("materialComposition", tempBean.getMaterialComposition());
        			// 数量
        			map.put("indentQuantity", tempBean.getIndentQuantity());
        			// 单价
        			map.put("indentPrice", tempBean.getIndentPrice());
        			// 总价
        			map.put("indentAmount", tempBean.getIndentAmount());
        			//map.put("planMaterialLoss", num.format(tempBean.getPlanMaterialLoss().doubleValue()));
        			dataList.add(map);
        		}
        	}
		}else if (specimenProductionList != null && specimenProductionList.size() > 0) {
			BigDecimal price = null;
			for (int i = 0; i < specimenProductionList.size(); i++) {
        		if (specimenProductionList.get(i) != null) {
        			map = new HashMap<String, Object>();
        			tempBean_SP = specimenProductionList.get(i);
        			// 款式编号
        			map.put("styleCustomerNo", tempBean_SP.getStyleNo());
        			// 款式名称
        			map.put("styleNameCN", tempBean_SP.getStyleNameCn());
        			// 成分
        			map.put("materialComposition", tempBean_SP.getMaterialComposition());
        			// 数量
        			map.put("indentQuantity", tempBean_SP.getSampleQuantity());
        			// 单价
        			price = tempBean_SP.getSampleMandayCost().add(tempBean_SP.getSampleMaterialCost()).add(tempBean_SP.getSampleOtherCost());
        			map.put("indentPrice", price);
        			// 总价
        			map.put("indentAmount", price.multiply(new BigDecimal(tempBean_SP.getSampleQuantity())));
        			dataList.add(map);
        		}
        	}
		}else if (orderList != null && orderList.size() > 0) {
			for (int i = 0; i < orderList.size(); i++) {
        		if (orderList.get(i) != null) {
        			map = new HashMap<String, Object>();
        			tempBean_O = orderList.get(i);
        			// 款式编号
        			map.put("styleCustomerNo", tempBean_O.getOrderNO());
        			// 款式名称
        			map.put("styleNameCN", tempBean_O.getStyleNameCN());
        			// 成分
        			map.put("materialComposition", tempBean_O.getMaterialComposition());
        			// 数量
        			map.put("indentQuantity", 1);
        			// 单价
        			map.put("indentPrice", tempBean_O.getCost());
        			// 总价
        			map.put("indentAmount", tempBean_O.getCost());
        			dataList.add(map);
        		}
        	}
		}else {
			map = new HashMap<String, Object>();
			// 款式编号
			map.put("styleCustomerNo", "");
			// 款式名称
			map.put("styleNameCN", "");
			// 成分
			map.put("materialComposition", "");
			// 数量
			map.put("indentQuantity", "");
			// 单价
			map.put("indentPrice", "");
			// 总价
			map.put("indentAmount", "");
			dataList.add(map);
		}
        // 向excel表输出
        handle.writeListDataCustom(tempFilePath, dataCellDeclare, dataList, 0, -1, "true" , 10);
    }
    /**
	  * @Title: saveSettlement
	  * @Description: 保存
	  * @param @param settlement
	  * @return void 
	  * @throws
	  *//*
	@Transactional(readOnly = false)
	public void saveSettlement(Settlement settlement) throws Exception{
		settlement.preInsert();
		if (settlement.getFinanceInvoiceEntity()!=null) {
			settlement.getFinanceInvoiceEntity().preInsert();
			financeInvoiceEntityMapper.insert(settlement.getFinanceInvoiceEntity());
		}
		settlement.setSettlementStatus(ResourcesUtil.getConfig("exchange_es10"));
		exchangeFormEntityMapper.updateCreateInfo(settlement);
		if (settlement.getSettlementList() != null && settlement.getSettlementList().size()>0) {
			for (int i = 0; i < settlement.getSettlementList().size(); i++) {
				settlement.getSettlementList().get(i).preInsert();
				orderDao.updateOrderStatus(settlement.getSettlementList().get(i));
				int orderNum = orderDao.getOrderNum(settlement.getSettlementList().get(i));
				if (orderNum == 0) {
					orderDao.updateContractStatus(settlement.getSettlementList().get(i));
				}
			}
		}
	}*/
	
	/**
	  * @Title: saveSettlement
	  * @Description: 保存
	  * @param @param settlement
	  * @return void 
	  * @throws
	  */
	@Transactional(readOnly = false)
	public void saveFinance(FinanceEntity financeEntity) throws Exception{
		financeEntity.preInsert();
		financeEntity.setAccountsStatus(ResourcesUtil.getConfig("financeStatus02"));
		financeEntity.setSettlementStatus(ResourcesUtil.getConfig("settlementStatus02"));
		financeEntity.setAuditStatus(ResourcesUtil.getConfig("reserver_meterial_wait_accept"));
		financeEntityMapper.insert(financeEntity);
	}
	
	/**
	 * 获取客户集
	 * @return List<Ognization>
	 */
	public List<Ognization> findOgnizationList(){
		return ognizationDao.findCuSuList(new Ognization());
	}
	
	/**
     * @Title: findAuditList
     * @Description: 查询所有履历
     * @param @param auditInfo
     * @param @return
     * @return List<AuditInfo> 
     * @throws
     */
   public AuditInfo findAuditInfo(AuditInfo auditInfo) {
	   AuditInfo audit = new AuditInfo();
	   audit.setAuditList(auditInfoDao.findAllList(auditInfo));
	   audit.setAuditStatus(auditInfoDao.findAuditAcceptCount(auditInfo));
       // 执行查询
       return audit;
   }

   /**
    * @Title: getAuditResult
    * @Description: 审核结果
    * @param @param auditInfo
    * @param @return
    * @return 审核结果通过数
    * @throws
    */
  
  public long getAuditResult(AuditInfo auditInfo) {
	   
      return auditInfoDao.findAuditAcceptCount(auditInfo);
  }
  
  /**
	  * @Title: saveAudit
	  * @Description: 保存履历信息
	  * @param @param auditInfo
	  * @return void 
	  * @throws
	  */
	@Transactional(readOnly = false)
	public void saveAuditInfo(AuditInfo auditInfo,boolean isUpdateStatus) {
		
		 // 插入履历表
	     auditInfo.preInsert();
	     auditInfo.setAuditDate(new Date());
	     auditInfo.setAuditUserId(UserUtils.getUser().getId());
         // 新建版本号赋值1
	     auditInfo.setVersion(1L);
	     auditInfoDao.insert(auditInfo);
	     
	     auditInfo.preUpdate();
	     if (auditInfo.getAuditResult()==0) {
	    	 auditInfo.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_no"));
		}else if (auditInfo.getAuditResult()==1) {
			auditInfo.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
		}
	     
	     financeEntityMapper.updateStatus(auditInfo);
	     
	}
}
